<?php

namespace app\controller\api\v1\recovery;


use app\model\user\User;
use app\model\v1\gift\GiftCardShareLog;
use app\model\v1\gift\GiftCardUser;
use app\model\v1\recovery\ConfigServ;
use app\model\v1\recovery\RecoveryIndustry;
use app\model\v1\recovery\RecoveryProductQuote;
use app\model\v1\recovery\RecoveryProductShop;
use app\model\v1\recovery\RecoveryUserRelation;
use app\Request;
use app\model\v1\recovery\RecoveryProduct as productModel;
use app\model\v1\recovery\RecoveryUserSearchHistory;
use app\services\product\category\StoreProductCategoryServices;
use app\validate\api\recovery\imageValidate;
use app\validate\api\recovery\productCardValidate;
use app\validate\api\recovery\productShopValidate;
use app\validate\api\recovery\productValidate;
use app\validate\api\recovery\reportValidate;
use app\validate\api\recovery\shopValidate;

class RecoveryProduct
{

    protected $services;
    protected $model;
    protected $userinfo = [];


    public function __construct(StoreProductCategoryServices $services)
    {
        $this->services = $services;
        $this->model = new productModel();
    }


    /**
     * 首页 - 搜索 - 商品详情
     * @return \think\Response
     */
    public function getProductDetail(Request $request)
    {
        $id = $request->get('id', 0);
        if(empty($id))  return app('json')->fail('商品id不能为空');

        $param = $request->param();
        $param["user_id"] = $request->uid();

        try {
            //根据用户传入的商品id获取商品的详情信息
            $item = productModel::detail($id, $param);
            return app('json')->success($item);

        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 用户历史搜索删除
     * @param Request $request
     * @return \think\Response
     */
    public function deleteSearch(Request $request)
    {
        $param = $request->post();
        if(empty($param['topic']))  return app('json')->fail('topic不能为空');

        $param['uid'] = $request->uid();
        try {
            //根据用户id，将用户的历史搜索数据删除
            $res = RecoveryUserSearchHistory::deleteSearch($param);
            if($res >= 0){
                return app('json')->success(true);
            }
            return app('json')->fail('fail');

        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 首页 - 搜索 - 获取用户历史搜索
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function searchHistory(Request $request)
    {
        $param = $request->param();
        $param['topic'] = $param['topic'] ?? '2';
        $model = new RecoveryUserSearchHistory();

        //根据用户id获取用户的历史搜索热词的数据
        $data = $model->getUserSearchHistory($request->uid(),$param);
        return app('json')->success($data);
    }



    /**
     * 获取回收/搬家入驻列表
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DbException
     */
    public function getRecoveryShopList(Request $request)
    {
        //接收用户传参的参数
        $params = $request->param();
        $params["limit"] = $params['limit'] ?? 10;
        $params["page"] = $params['page'] ?? 1;

        //获取回收入驻/搬家入驻的列表
        $params["user_id"] = $request->uid();
        $data = productModel::getRecoveryShopList($params);

        return app('json')->success($data);
    }


    /**
     * 首页 - top区域 -获取轮播图
     * @return \think\Response
     */
    public function getConfigImage(Request $request)
    {

        $param = $request->postMore([
            ['show_position', ''],
            ['client_type', ''],
            ['cate_id', ''],
        ]);
        validate(imageValidate::class)->check($param);


        try {
            $item = productModel::getConfigImage($param);

            return app('json')->success($item);
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 首页 - 推荐位图
     * @return \think\Response
     */
    public function getConfigPageImg(Request $request)
    {
        $param = $request->postMore([
            ['show_position', ''],
            ['client_type', ''],
        ]);
        validate(imageValidate::class)->check($param);


        try {
            $item = productModel::getConfigPageImg($param);

            return app('json')->success($item);
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }





    /**
     * 个人中心 - 服务列表
     * @return \think\Response
     */
    public function getConfigServData(Request $request)
    {
        $param = $request->param();
        $param['client_type'] = $request->param("client_type", 2);

        try {
            $item = ConfigServ::getConfigServData($param);

            return app('json')->success($item);
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }




    /**
     * 个人中心 - 管理列表
     * @return \think\Response
     */
    public function getConfigManageData(Request $request)
    {
        $param = $request->param();
        $param['client_type'] = $request->param("client_type", 2);

        try {
            $item = ConfigServ::getConfigManageData($param);

            return app('json')->success($item);
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }



    /**
     * 首页 - 闲置发布 - 单品发布
     * @return \think\Response
     */
    public function publish(Request $request)
    {
        $param = $request->post();
        validate(productValidate::class)->check($param);

        $pattern = '/^\d+(?:\.\d{1,2})?$/';
        if(!preg_match($pattern, $param["price"])) return app('json')->fail('价格必须为数字，且小数点不能超过两位！');

        if($param["is_sale"] == 1){
            if(empty($param["pre_sale_date"])) return app('json')->fail('pre_sale_date起售时间字段必填');
        }

        $param["images"] = $request->post("images", "");
        $param['user_id'] = $request->uid();
        try {
            //用户闲置发布商品
            $res = productModel::addProduct($param);
            if($res > 0){
                return app('json')->success('success');
            }
            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    public function publishCard(Request $request)
    {
        $param = $request->post();
        validate(productCardValidate::class)->check($param);

        $pattern = '/^\d+(?:\.\d{1,2})?$/';
        if(!preg_match($pattern, $param["price"])) return app('json')->fail('价格必须为数字，且小数点不能超过两位！');

        if(!empty($param["is_sale"]) && $param["is_sale"] == 1){
            if(empty($param["pre_sale_date"])) return app('json')->fail('pre_sale_date起售时间字段必填');
        }

        $param["images"] = $request->post("images", "");
        $param['user_id'] = $request->uid();
        try {
            //用户闲置发布商品
            $res = productModel::addProductCard($param);
            if($res > 0){
                return app('json')->success('success');
            }
            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 卡类转让 - 编辑
     * @param Request $request
     * @return \think\Response
     */
    public function updatePublishCard(Request $request)
    {
        //校验用户传入的参数
        $param = $request->post();
        validate(productCardValidate::class)->check($param);

        $pattern = '/^\d+(?:\.\d{1,2})?$/';
        if(!preg_match($pattern, $param["price"])) return app('json')->fail('价格必须为数字，且小数点不能超过两位！');


        $param["images"] = $request->post("images", "");
        $param['user_id'] = $request->uid();
        try {
            //卡类编辑
            $res = productModel::updatePublishCard($param);
            if($res >= 0){
                return app('json')->success('success');
            }
            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 首页 - 闲置发布 - 发布店铺
     * @param Request $request
     * @return \think\Response|void
     */
    public function publishShop(Request $request)
    {
        $param = $request->post();
        validate(shopValidate::class)->check($param);

        //校验办公转租的参数校验
        if($param["type"] == 2) {
            if(empty($param["plege"])) return app('json')->fail('押付方式押字段必填');
            if(empty($param["symbol"])) return app('json')->fail('押付方式付字段必填');
            if(empty($param["number"])) return app('json')->fail('楼层房号字段必填');
            ////if(empty($param["use"])) return app('json')->fail('使用率字段必填且不能为0');
            $pattern = '/^\d+(?:\.\d{1,2})?$/';
            if(!preg_match($pattern, $param["use"])) return app('json')->fail('使用率必须为数字，且小数点不能超过两位！');
        }
        if($param["type"] == 1) {
            if(empty($param["logo"])) return app('json')->fail('logo店铺logo必填');
        }

        $param["img"] = $request->post("img", "");
        $param['user_id'] = $request->uid();
        try {
            $res = RecoveryProductShop::addProductShop($param);
            if($res > 0){
                return app('json')->success('success');
            }
            app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 用户举报
     * @param Request $request
     * @return \think\Response
     */
    public function createReport(Request $request)
    {
        $param = $request->post();
        validate(reportValidate::class)->check($param);
        if($param["cate"] <= 0) return app('json')->fail("cate不能小于等于0");
        if(empty($param["module"])) return app('json')->fail("module不能为空");

        $param['user_id'] = $request->uid();
        try {
            $res = RecoveryProductShop::createReport($param);
            if($res > 0){
                return app('json')->success('success');
            }

            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 获取分享链接url -
     * @param Request $request
     * @return \think\Response
     */
    public function systemShareLink(Request $request)
    {
        $param = $request->param();
        if(empty($param["type"])) return app('json')->fail('type必填');
        $type = $param["type"];
        $uid = $param["uid"]??null;
        $time_id = $param["time_id"]??null;
        $types = $param["types"]??null;
	    $share_code=null;
		if ($uid){
			$share_code = User::getUserShareCode($uid);
		}
        if(empty($param["goods_id"])) return app('json')->fail('goods_id必填');
        $goods_id = $param["goods_id"] ?? '';

//        $data['link_url'] = 'https://h5.shangbaijie.com/water_details?goods='.$goods_id . '&share_code=' . $share_code.'&spid=' . $uid;
        //水站
        $url = '&share_code=' . $share_code.'&spid=' . $uid.'&type='.$types.'&time_id='.$time_id;
        if($type == 1){
	        $data['link_url'] = 'https://h5.shangbaijie.com/water_details?goods='.$goods_id .$url;
	        $data['link_url1'] = '/pages/supmarket/details?goods='.$goods_id .$url;
	        $data['share_type'] = '1';
        }

//        //超市
//        if($type == 2) $data['link_url'] = 'https://h5.shangbaijie.com/water_details?goods='.$goods_id .$url;
//        //礼品卡
//        if($type == 3) $data['link_url'] = 'https://h5.shangbaijie.com/gift_card_details?id='.$goods_id . $url;
//        //闲置转让
//        if($type == 4) $data['link_url'] = 'https://h5.shangbaijie.com/idleDetails?id='.$goods_id . $url;
//        //求职招聘
//        if($type == 5) $data['link_url'] = 'https://h5.shangbaijie.com/invite_details?item='.$goods_id . $url;
        //积分商城
        if($type == 6) $data['link_url'] = 'https://h5.shangbaijie.com/point_goods_details?goods='.$goods_id. $url;
		//人才
//		if($type == 7) $data['link_url'] = 'https://h5.shangbaijie.com/biographical_notes?item={"id":'.$goods_id. '}'.$url;

        //活动详情
		if($type == 8){
			$data['link_url1'] = 'pages/activity/goods_details/index?id='.$goods_id.$url;
			$data['share_type'] = '1';
		}


        return app('json')->success($data);
    }


    /**
     * 获取分享链接url - 我的礼品卡详情
     * @param Request $request
     * @return \think\Response
     */
    public function systemShareGiftLink(Request $request)
    {
        $uid = $request->uid();
        $share_code = User::getUserShareCode($uid);
        $encryptID = $request->param("encryptID", '');
        if(empty($encryptID)) return app('json')->fail('encryptID不能为空');

        $user_card_all = GiftCardUser::where("uid", $uid)->select()->toArray();
        $card_user_id = 0;
        foreach ($user_card_all as $key => $val){
            if(md5($val["id"] . GiftCardUser::ENCRYPTID) == $encryptID){
                $card_user_id = $val["id"];
                break;
            }
        }
        if(empty($card_user_id)) return app('json')->fail('参数fail');

        $data['link_url'] = 'h5.shangbaijie.com/accept_card?card_user_id='.$card_user_id. '&share_code=' . $share_code;

        $add = [
            "uid" => $uid, //用户id
            "card_user_id" => $card_user_id,
            "type" => 1,
            "create_time" => time(),
        ];
        GiftCardShareLog::create($add);
        return app('json')->success($data);
    }



    /**
     * 获取分享链接url - 分享邀请新用户注册
     * @param Request $request
     * @return \think\Response
     */
    public function systemShareRegisterLink(Request $request)
    {
        $uid = $request->uid();
        $share_code = User::getUserShareCode($uid);
        $data['link_url'] = 'https://h5.shangbaijie.com/home?share_code=' . $share_code.'&spid=' . $uid;
        $data['link_url1'] = '/pages/home/home?share_code=' . $share_code.'&spid=' . $uid;
        return app('json')->success($data);
    }



    /**
     * 首页 - 发布店铺/办公转租 - 获取行业数据类型列表
     * @param Request $request
     * @return \think\Response
     */
    public function getIndustryConfigList(Request $request)
    {
        try {
            $param = $request->param();

            //获取后台录入配置好的数据
            $data = RecoveryIndustry::getIndustryData(0);

            return app('json')->success($data);
        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 个人商家主页详情
     * @param Request $request
     * @return \think\Response
     */
    public function getUserShopDetail(Request $request)
    {
        $param = $request->param();
        if(empty($param['user_id']))  return app('json')->fail('user_id不能为空');
        //if(empty($param['category_id']))  return app('json')->fail('category_id不能为空');

        $param["uid"] = $request->uid();
        try {
            $item = productModel::getUserShopDetail($param);

            return app('json')->success($item);
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 首页 - 商品列表
     * @param Request $request
     * @return \think\Response
     */
    public function getCateProductList(Request $request)
    {
        $params = $request->param();
        if(empty($params["category_id"])) return app('json')->fail('category_id不能为空！');
        $params["limit"] = $params['limit'] ?? 10;
        $params["page"] = $params['page'] ?? 1;

        $params["user_id"] = $request->uid();
        $data = productModel::getCateProductList($params);

        return app('json')->success($data);
    }


    /**
     * 我的收藏 - 批量删除收藏
     * @param Request $request
     * @return \think\Response
     */
    public function collectCancel(Request $request)
    {
        $id = $request->post('ids');
        if (empty($id))  return app('json')->fail('id数组不能为空');

        $id = explode(",", $id);
        try {

            //在我的收藏中，点击管理对多个收藏的商品进行批量删除
            $res = (new RecoveryUserRelation())->whereIn('id', $id)->where("uid", $request->uid())->delete();
            if($res >= 0){
                return app('json')->success('success');
            }

            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 个人中心 - 获取个人实名认证详情
     * @param Request $request
     * @return \think\Response
     */
    public function getRegAuthentDetail(Request $request)
    {
        $param = $request->param();
        $param["user_id"] = $request->uid();
        try {
            $item = productModel::getRegAuthentDetail($param);
            return app('json')->success($item);

        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 个人中心 - 我发布的 - 店铺(办公转租)编辑
     * @param Request $request
     * @return \think\Response
     */
    public function updatePublishShop(Request $request)
    {
        $param = $request->post();
        validate(productShopValidate::class)->check($param);
        if($param["type"] == 2) {
            if(empty($param["plege"])) return app('json')->fail('押付方式押字段必填');
            if(empty($param["symbol"])) return app('json')->fail('押付方式付字段必填');
            if(empty($param["number"])) return app('json')->fail('楼层房号字段必填');
            ////if(empty($param["use"])) return app('json')->fail('使用率字段必填且不能为0');
            $pattern = '/^\d+(?:\.\d{1,2})?$/';
            if(!preg_match($pattern, $param["use"])) return app('json')->fail('使用率必须为数字，且小数点不能超过两位！');
        }
        if($param["type"] == 1) {
            if(empty($param["logo"])) return app('json')->fail('logo店铺logo必填');
        }

        $param["img"] = $request->post("img", "");
        $param['user_id'] = $request->uid();
        try {
            $res = RecoveryProductShop::updateProductShop($param);
            if($res >= 0){
                return app('json')->success('success');
            }

            return app('json')->fail('fail');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 用户添加收藏
     * @param Request $request
     * @return \think\Response
     */
    public function collect(Request $request)
    {
        $productId = $request->post('product_id');  //商品id
        $is_collect = $request->post('is_collect');  // 1收藏 2取消收藏
        $type = $request->post('type') ?? 'collect';
        if (empty($productId)) return app('json')->fail('product_id商品id不能为空');
        if (empty($is_collect)) return app('json')->fail('is_collect字段不能为空');

        try {
            RecoveryUserRelation::collect($productId, $request->uid(), $is_collect, $type);

            return app('json')->success('success');
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 校验是否已报价
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkIsQuote(Request $request)
    {
        $param = $request->param();
        if (empty($param['product_id'])) return app('json')->fail('is_collect字段不能为空');

        $find = RecoveryProductQuote::where(['uid'=>$request->uid(), 'product_id'=>$param['product_id']])->whereNotIn("status", [4,5,6])->find();

        return app('json')->success($find ? $find->toArray() : []);
    }


    /**
     * 用户报价
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function quote(Request $request)
    {
        $param = $request->post();
        if (empty($param['product_id'])) return app('json')->fail('product_id字段不能为空');
        if (empty($param['quote_price'])) return app('json')->fail('quote_price字段不能为空');
        if (empty($param['shop_id'])) return app('json')->fail('shop_id字段不能为空');

        $find = RecoveryProductQuote::where(['uid'=>$request->uid(), 'product_id'=>$param['product_id']])->whereNotIn("status", [4,5,6])->find();
        if(!empty($find)) return app('json')->fail('不能重复报价！');

        $param['user_id'] = $request->uid();
        $res = RecoveryProductQuote::createOne($param);
        if($res > 0){
            return app('json')->success('报价成功');
        }

        return app('json')->fail('fail');
    }


    /**
     * 获取静态文件显示的origin
     * @param Request $request
     * @return \think\Response
     */
    public function getAppImgOrigin(Request $request)
    {
        $data = ["origin" => "https://picture.shangbaijie.com/"];  //https://photo.shangbaijie.com/
        return app('json')->success($data);
    }




}